<?php
class MyFilesController extends AppController {

	var $name = 'MyFiles';
    var $components = array('Uploader.Uploader');
	function index() {
		$this->MyFile->recursive = 0;
		$this->set('myFiles', $this->paginate());
	}
	function beforeFilter(){
        $this->Uploader->uploadDir = 'files/uploads/'; //thu muc chua file upload
        $this->Uploader->enableUpload = true;
        $this->Uploader->maxFileSize = '2M'; // quy dinh dung luong duoc upload len toi da la 2 Megabytes
        $this->Uploader->maxNameLength = 25;//do dai cua ten file
        $this->Uploader->tempDir = TMP;
        //$this->Uploader->mime('image', 'gif', 'image/gif');
    }

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid my file', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('myFile', $this->MyFile->read(null, $id));
	}
	function upload() {
    if (!empty($this->data)) {
         if ($data = $this->Uploader->upload('fileName')) {
         	echo "Upload thanh cong";
		//do something;
         }else{
		echo "Co loi xay ra! Vui long thu lai!";
	 }	
    }
}
    function download($id) {
    Configure::write('debug', 0);
    $file = $this->MyFile->findById($id);

    header('Content-type: ' . $file['MyFile']['type']);
    header('Content-length: ' . $file['MyFile']['size']); // some people reported problems with this line (see the comments), commenting out this line helped in those cases
    header('Content-Disposition: attachment; filename="'.$file['MyFile']['name'].'"');
    echo $file['MyFile']['data'];

    exit();
}

	function add() {
		  if (!empty($this->data) &&
             is_uploaded_file($this->data['MyFile']['File']['tmp_name'])) {
            $fileData = fread(fopen($this->data['MyFile']['File']['tmp_name'], "r"),
                                     $this->data['MyFile']['File']['size']);

            $this->data['MyFile']['name'] = $this->data['MyFile']['File']['name'];
            $this->data['MyFile']['type'] = $this->data['MyFile']['File']['type'];
            $this->data['MyFile']['size'] = $this->data['MyFile']['File']['size'];
            $this->data['MyFile']['data'] = $fileData;

        //    $this->MyFile->save($this->data);

            $this->redirect(array('action' => 'index'));
        }
    }

	
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for my file', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->MyFile->delete($id)) {
			$this->Session->setFlash(__('My file deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('My file was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
